package com.smartsofa.main;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.entity.Topic;
import com.smartsofa.photo.Bimp;
import com.smartsofa.photo.GridClassify;
import com.smartsofa.photo.PhotoDelete;
import com.smartsofa.photo.PhotoScan;
import com.smartsofa.util.MyUtils;

public class PublishTopic extends Activity {
	
	private Button bt_back;
	private Button bt_submit;
	private EditText et_topic;
	private Boolean flag=false;
	private GridView noScrollgridview;
	private GridAdapter adapter;
	private Bitmap photo;
	JSONObject jsonObject;
	private String[] classify = null;
	private int classifyid = 0;
	private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
	private Intent intent;
	private String path = "";
	private	String picPath = "";
	private static final int REQUEST_TIMEOUT = 6 * 1000;// ��������ʱ6����
	private int classify_flag = 0;
	private int hos_flag = 0;
	private int doc_flag = 0;
	private int same_flag = 0;
	private int photo_flag = 0;
	private int content_flag = 0;
	private int clubid=0;
	private int doctorid=0;
	private int idoctor;
	private GridClassify menuWindow;
	private TextView tv;
	private EditText title;
	private EditText content;
	private String[] samecircle = null;
	private String[] hoscircle = null;
	private String[][] doctors = null;
	private List<String> bmp=null;
	private List<String> photoname=null;
	private String photostr=null;
	private String phototitle=null;
	private String imageurl=null;
	Topic topic=new Topic();
	
	private String url;
	private ProgressDialog mDialog;	
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.publish_topic);	
		intiateView();
		}
	private void intiateView(){
		bt_back=(Button) findViewById(R.id.back);
		bt_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Bimp.bmp.clear();
				Bimp.drr.clear();
				Bimp.max = 0;
				PublishTopic.this.finish();
			}
		});
		et_topic=(EditText) findViewById(R.id.et_topic);
		bt_submit=(Button) findViewById(R.id.submit);
		bt_submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub				
				publishTopic();
			}
		});
		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.bmp.size()) {
					
					new AlertDialog.Builder(PublishTopic.this)
					.setTitle("添加图片")
					.setItems(new String[] { "相机拍摄", "手机相册" }, new DialogInterface.OnClickListener() {   
	    
	                    @Override   
	                    public void onClick(DialogInterface dialog, int which) {   
	                    	if(which == 0) {         
	                    		//添加拍照动作
	                            destoryBimap();
								String state = Environment.getExternalStorageState();
								if (state.equals(Environment.MEDIA_MOUNTED)) {
									Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
	                            	startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
								} else {
									Toast.makeText(PublishTopic.this,"请插入SD卡", Toast.LENGTH_LONG).show();
								}
	                    	} else {
	                    		//添加本地图片
	                    		Intent intent = new Intent(PublishTopic.this, PhotoScan.class);
	                    		startActivity(intent);
	                    	    
	                    	}
	                    }   
	                })
					.setNegativeButton("取消", null).show();
				} else {
					Intent intent = new Intent(PublishTopic.this,PhotoDelete.class);
					intent.putExtra("ID", arg2);
					startActivity(intent);
					
				}
			}
		});
		
	}
	
	private void publishTopic(){
		mDialog = new ProgressDialog(PublishTopic.this);
		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mDialog.setMessage("正在处理，请稍候...");
		mDialog.show();
		String et_topicContent=et_topic.getText().toString();
		if(et_topicContent.equals("")){
			Toast.makeText(getApplicationContext(), "至少写点什么吧……", Toast.LENGTH_SHORT).show();
		}
		else{
			topic.setTopicContent(et_topicContent);
			topic.setUserId(MyUtils.getUSERID());
			Thread thread=new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					
					try {
						if( Bimp.bmp.size()!=0){
						bmp = new ArrayList<String>();				
						for (int i = 0; i < Bimp.bmp.size(); i++) {
							Bitmap bit = Bimp.bmp.get(i);
							bmp.add(convertIconToString(bit));				
						}
						//photostr=convertIconToString(Bimp.bmp.get(0));
						photostr = bmp.get(0);
						photoname = new ArrayList<String>();				
						for (int i = 0; i < Bimp.drr.size(); i++) {
							String Str = Bimp.drr.get(i).substring( 
									Bimp.drr.get(i).lastIndexOf("/") + 1,
									Bimp.drr.get(i).lastIndexOf("."));
							photoname.add(Str+".PNG");				
						}
						phototitle=Bimp.drr.get(0).substring( 
								Bimp.drr.get(0).lastIndexOf("/") + 1,
								Bimp.drr.get(0).lastIndexOf("."))+".PNG";
						
						
					
						}
						String topicContent=topic.getTopicContent().replaceAll(" ", "%20");;						
						String urlString = MyUtils.getUrl()+"topic_postTopic";
						HttpPost post = new HttpPost(new URI(urlString));
						JSONObject json = new JSONObject();
					
						json.put("fileData",photostr);	
						json.put("userId", MyUtils.getUSERID());
						json.put("topicContent", topicContent);
						post.setEntity(new StringEntity(json.toString(),"utf-8"));
						BasicHttpParams httpParams = new BasicHttpParams();
						HttpConnectionParams.setConnectionTimeout(httpParams,3000);
						HttpClient httpClient = new DefaultHttpClient(httpParams);
						HttpResponse httpResponse = httpClient.execute(post);				       
					    Log.i("tiezimsg", "image to server begin,,,,,,");
					    if (httpResponse.getStatusLine().getStatusCode() == 200) {					    	
					        String jsonString = EntityUtils.toString(httpResponse.getEntity());
					        Log.i("back jsonString",jsonString);
					        jsonObject = new JSONObject(jsonString);
					        flag=(Boolean)jsonObject.get("success");	
					    }
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Message msg = content_handler.obtainMessage();
					if (flag) {				
						msg.what = 1;									
					}
					else{
						msg.what = 2;						
					}
					content_handler.sendMessage(msg);
				}
			});
			thread.start();
		}		
	}
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {
			mDialog.dismiss();
			switch (msg.what) {		
			case 1:
				Intent intent=new Intent();
				Bundle bundle=new Bundle();
				bundle.putInt("selectionState", 1);
				intent.putExtra("attachment",bundle);
				try {
					String imageurl=jsonObject.getString("imageurl");
					Log.i("imageurl", imageurl);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				intent.setClass(PublishTopic.this, MainActivity.class);		
				startActivity(intent);	
				PublishTopic.this.finish();
				Toast.makeText(getApplicationContext(), "发表说说成功！", Toast.LENGTH_SHORT).show();
				break;
			case 2:
				Toast.makeText(getApplicationContext(), "发表失败，请稍后尝试！", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	public class GridAdapter extends BaseAdapter {

		private LayoutInflater inflater; // ��ͼ����
		private int selectedPosition = -1;// ѡ�е�λ��
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			return (Bimp.bmp.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item����
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.bmp.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 8) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.bmp.get(position));
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.drr.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							try {
								String path = Bimp.drr.get(Bimp.max);
								//System.out.println(path);
								Bitmap bm = Bimp.revitionImageSize(path);
								Bimp.bmp.add(bm);
							/*	String newStr = path.substring(
										path.lastIndexOf("/") + 1,
										path.lastIndexOf("."));*/
							
								Bimp.max += 1;
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
							} catch (IOException e) {

								e.printStackTrace();
							}
						}
					}
				}
			}).start();
		}

}
	/**
	 * 销毁图片文件
	 */
	private void destoryBimap() {
		if (photo != null && !photo.isRecycled()) {
			photo.recycle();
			photo = null;
		}
	}
	
	
    protected void onRestart() {
		adapter.update();
		super.onRestart();
	}
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data); 
		if (resultCode != RESULT_OK) {
			return;
		} else switch (requestCode) {
        case PHOTO_REQUEST_TAKEPHOTO:
        	  Uri uri = data.getData();
        	if(uri == null){
        		Bundle bundle = data.getExtras();
        		if(bundle!=null){
        		photo= (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式 			 
                FileOutputStream b = null;   
                 File file = new File("/sdcard/myImage/");  
                 file.mkdirs();// 创建文件夹  
                 String name = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";  
                 String fileName = "/sdcard/myImage/"+name;     
                 try {  
                     b = new FileOutputStream(fileName);  
                     photo.compress(Bitmap.CompressFormat.PNG, 100, b);// 把数据写入文件  
                 } catch (FileNotFoundException e) {  
                     e.printStackTrace();  
                 } finally {  
                     try {  
                         b.flush();  
                         b.close();  
                     } catch (IOException e) {  
                         e.printStackTrace();  
                     }  
                 }
                 picPath=fileName;
        		}
        	}      	
        	else{
   			
   			try {
   				String[] pojo = {MediaStore.Images.Media.DATA};
   				Cursor cursor = managedQuery(uri, pojo, null, null,null);
   				if(cursor!=null){
   					int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   					cursor.moveToFirst();
   					String path = cursor.getString(colunm_index);
   					if(path!=null){
   						picPath=path;
   					}
   				}
   			}catch (Exception e) {
   				// TODO: handle exception
   			 }
        	}
   			if (Bimp.drr.size() < 8 && resultCode == -1) {
				Bimp.drr.add(picPath);
			}
   		//	adapter.update();
            break;
        }
		super.onActivityResult(requestCode, resultCode, data);
	}
    /**  
     * 图片转成string  
     *   
     * @param bitmap  
     * @return  
     */  
    public static String convertIconToString(Bitmap bitmap)  
    {  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream  
        bitmap.compress(CompressFormat.PNG, 100, baos);  
        byte[] appicon = baos.toByteArray();// 转为byte数组  
        return Base64.encodeToString(appicon, Base64.DEFAULT);  
    }

}
